package br.com.mtg.movethegarbage.impl;

import android.graphics.RectF;
import br.com.mtg.movethegarbage.framework.GUIBase;
import br.com.mtg.movethegarbage.framework.Game;
import br.com.mtg.movethegarbage.framework.GameTouchEvent;
import br.com.mtg.movethegarbage.framework.Graphics;
import br.com.mtg.movethegarbage.game.Assets;
import br.com.mtg.movethegarbage.graphics.Sprite;
import br.com.mtg.movethegarbage.graphics.SpriteManager;

public class Button extends GUIBase
{
	String buttonString;
	float fontSize;
	boolean pressed = false;
	boolean pressing = false;
	int touchPointerId;
	Sprite buttonSprite;

	public Button(float _x, float _y, float _w, float _h)
	{
		super(_x, _y, _w, _h);
		touchPointerId = -1;
		buttonString = "";
	}

	public Button(float _x, float _y, String _buttonString, float _fontSize, Sprite buttonSprite)
	{
		x = _x;
		y = _y;
		fontSize = _fontSize;
		setButtonString(_buttonString);
		setButtonSprite(buttonSprite);
	}

	@Override
	public void draw(Graphics graphics)
	{
		if (w == 0 && h == 0)
			return;
		SpriteManager spriteManager = new SpriteManager(graphics, 1);
		spriteManager.beginDraw(buttonSprite.texture);
		spriteManager.drawSprite(x, y, w, h, buttonSprite);
		spriteManager.endDraw();
		if (!buttonString.equals(""))
		{
			Assets.font.setScale(fontSize);
			Assets.font.printAt(buttonString, x + 10, y + 5);
		}
	}

	@Override
	public void handleEvent(Object _event, Game game)
	{
		GameTouchEvent event = (GameTouchEvent) _event;
		RectF rect = getRect();
		if (event.type == GameTouchEvent.TOUCH_DOWN)
		{
			if (rect.contains(event.touchX, event.touchY) && pressing != true)
			{
				x -= 10;
				y -= 10;
				w += 5 * (buttonString.length() == 0 ? 2 : buttonString.length());
				h += 10;
				fontSize += 0.20F;
				touchPointerId = event.pointerID;
				pressing = true;
				game.getAudio().playSound(Assets.clickSound, 0.3F);
			}
		}
		else if (event.type == GameTouchEvent.TOUCH_UP)
		{
			if (touchPointerId != -1 && touchPointerId == event.pointerID && pressing == true)
			{
				x += 10;
				y += 10;
				w -= 5 * (buttonString.length() == 0 ? 2 : buttonString.length());
				h -= 10;
				fontSize -= 0.20F;
				touchPointerId = -1;
				pressed = true;
				pressing = false;
			}
		}
	}

	public void setButtonString(String _buttonString)
	{
		buttonString = _buttonString;
		Assets.font.setScale(fontSize);
		h = Assets.font.getTextHeight() + 10;
		w = Assets.font.getTextLength(buttonString) + 20;
	}

	public void setFontSize(float _fontSize)
	{
		fontSize = _fontSize;
	}

	public void setButtonSprite(Sprite sprite)
	{
		buttonSprite = sprite;
	}

	public Sprite getButtonSprite()
	{
		return buttonSprite;
	}

	public String getButtonString()
	{
		return buttonString;
	}

	public boolean wasPressed()
	{
		if (pressed)
		{
			pressed = false;
			return true;
		}
		else
			return false;
	}
}
